package org.kl.bf.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 根据模板自动生成Word
 */
public class AutoCreateDoc {

	private Configuration configuration = null;

	public AutoCreateDoc() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
	}

	/**
	 * filePath,存放位置
	 * dataMap,要填入模本的数据文件
	 * outFile,输出文档路径及名称
	 */
	public void createDoc(String tempFilePath, Map<String, Object> dataMap, String outFile) {
		File f = new File(tempFilePath);
		try {
			// 模板路径
			configuration.setDirectoryForTemplateLoading(new File(f.getParent()));
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		Template t = null;
		try {
			// 模板名称
			t = configuration.getTemplate(f.getName());
			t.setEncoding("utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 输出文档路径及名称
		File otf = new File(outFile);
		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(otf), "utf-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			t.process(dataMap, out);
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * filePath,存放位置
	 * dataMap,要填入模本的数据文件
	 * outputStream,输出文件流
	 */
	public void createDoc(String tempFilePath, Map<String, Object> dataMap, OutputStream outputStream) {
		File f = new File(tempFilePath);
		try {
			// 模板路径
			configuration.setDirectoryForTemplateLoading(new File(f.getParent()));
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		Template t = null;
		try {
			// 模板名称
			t = configuration.getTemplate(f.getName());
			t.setEncoding("utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 输出文档路径及名称
		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			t.process(dataMap, out);
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Template temp(File f) {
		try {
			// 模板路径
			configuration.setDirectoryForTemplateLoading(new File(f.getParent()));
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		Template t = null;
		try {
			// 模板名称
			t = configuration.getTemplate(f.getName());
			t.setEncoding("utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return t;
	}
}